package fms.dao;

import fms.model.CptInfo;
import fms.util.DateUtil;
import fms.util.SysConstants;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.ParseException;
import java.util.List;

@Service("cptInfoService")
public class CptInfoServiceImpl implements CptInfoService {
    private Logger windCalcLogger = Logger.getLogger("windCalc");

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private CptInfoDao cptInfoDao;

    // 新增
    // 自动提交事务
    @Transactional
    public CptInfo save(CptInfo cptInfo) {
        return cptInfoDao.save(cptInfo);
    }

    @Transactional
    public Iterable<CptInfo> save(Iterable<CptInfo> cptInfo) {
        return cptInfoDao.save(cptInfo);
    }

    // 新增 + 更新
    @Transactional
    public CptInfo update(CptInfo cptInfo) {
        return cptInfoDao.saveAndFlush(cptInfo);
    }

    @Override
    public long count() {
        return cptInfoDao.count();
    }

    @Transactional
    @Override
    public void delete(CptInfo cptInfo) {
        cptInfoDao.delete(cptInfo);
    }

    @Transactional
    @Override
    public void deleteById(int id) {
        cptInfoDao.deleteById(id);
    }


    @Transactional
    @Override
    public void deleteAll() {
        cptInfoDao.deleteAll();
    }

    @Override
    public Iterable<CptInfo> findAll() {
        return cptInfoDao.findAll();
    }

    @Override
    public CptInfo findById(int id) {
        return cptInfoDao.findById(id);
    }

    @Override
    public List<CptInfo> findByCptnameLike(String cptnamelike) {
        return cptInfoDao.findByCptnameLike(cptnamelike);
    }

    @Override
    public void saveOrUpdate(List<CptInfo> cptInfoList){
        if(cptInfoList != null && cptInfoList.size() > 0){
            for(CptInfo cptInfo : cptInfoList){
                List<CptInfo> cptInfos = cptInfoDao.findCptSend2(cptInfo.getFlightId(), cptInfo.getAircraftId(), cptInfo.getPlanId());
                if(cptInfos != null && cptInfos.size() > 0){
                    for (CptInfo c : cptInfos){
                        cptInfoDao.delete(c);
                    }
                }
            }

            cptInfoDao.save(cptInfoList);
        }
    }

    // 取得航路点的经度、纬度
    @Override
    public List findByCptname(String cptname, String aircraftId, String flightId ) {
        String curUTCTime = DateUtil.getCurUTCtime(SysConstants.FORMAT_DATETIME_FULL);
        String flyPlanValidTime = null;
        try {
            flyPlanValidTime = DateUtil.changeDay(curUTCTime, -2, SysConstants.FORMAT_DATETIME_FULL);
        } catch (ParseException e) {
            windCalcLogger.error("CptInfoServiceImpl-findByCptname:获取24小时前的UTC时刻失败！");
        }
        StringBuffer str = new StringBuffer();
        str.append("    select u.lon, u.lat ");
        str.append("    from cpt_info u ");
        str.append("    where u.CPT_NAME = :cptName ");
        str.append("    and u.aircraft_id= :aircraftId" );
        // 仅使用2天以内的飞行计划，trunc和sysdate方式不精确
//        str.append("    and trunc(plan_date)>=trunc(sysdate-2) ");
        str.append("    and  u.plan_date >= to_date(:date, 'yyyy-MM-dd hh24:mi:ss')");
        str.append("    and  u.flight_id=:flightId ");
        str.append("    order by plan_date desc ");

        Query query = em.createNativeQuery(str.toString());
        query.setParameter("cptName", cptname);
        query.setParameter("aircraftId", aircraftId);
        query.setParameter("flightId", flightId);
        query.setParameter("date", flyPlanValidTime);

//        windCalcLogger.debug("查询航路点(" + cptname + ")经纬度数据");
//        windCalcLogger.debug("航路点经纬度查询sql:" + str);

//System.out.println(str);
        return query.getResultList();
    }

    // 取得去重后航班计划ID列表
    @Override
    public List getPlanIdList() {
        String curUTCTime = DateUtil.getCurUTCtime(SysConstants.FORMAT_DATETIME_FULL);
        String flyPlanValidTime = null;
        try {
            flyPlanValidTime = DateUtil.changeDay(curUTCTime, -2, SysConstants.FORMAT_DATETIME_FULL);
        } catch (ParseException e) {
            windCalcLogger.error("CptInfoServiceImpl-getPlanIdList:获取24小时前的UTC时刻失败！");
        }

        StringBuffer str = new StringBuffer();
        str.append("    select distinct(PLAN_ID) ");
        str.append("    from cpt_info");
        // 仅使用2天以内的飞行计划，trunc和sysdate方式不精确
//        str.append("    and trunc(plan_date)>=trunc(sysdate-2) ");
        str.append("    where plan_date >= to_date(:date, 'yyyy-MM-dd hh24:mi:ss')");
//System.out.println(flyPlanValidTime);
        Query query = em.createNativeQuery(str.toString());
        query.setParameter("date", flyPlanValidTime);

        return query.getResultList();
    }

}
